<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组方法的使用</title>
</head>
<body>
    <script>
        // 数组求和
        const arr = [1,2,3,4,5,6]
        const sum = arr.reduce((prev, cur, index,arr) => {
            console.log(prev,cur,index);
            return prev + cur
        })
        const sum1 = arr.reduce((prev,cur) => prev + cur)

        // 数据求积
        const multip = arr.reduce((prev,cur) => prev * cur)
        // console.log('arr:',arr,'sum:',sum, 'sum1:',sum1, 'multip:',multip)

        // 计算数组中每个元素出现的次数
        var names = ['Alice','Bob','Tiff','Bruce','Alice','Bob','Bob']
        var countedNames = names.reduce((prev,cur) => {
            if(cur in prev){
                prev[cur]++;
            }else{
                prev[cur] = 1;
            }
            return prev;
        },{})
        // console.log('countedNames:',countedNames)

        // 去除数组中的重复元素
        let myArray = ['a','b','a','b','c','e','e','c','d','d','d','d'];
        // 方法一
        let myOrderedArray = myArray.reduce((prev,cur) => {
            // 方法一：indexOf
            // if(prev.indexOf(cur) === -1){
            //     prev.push(cur)
            // }
            // 方法二：filter
            // if(prev.filter(item => item === cur).length === 0){
            //     prev.push(cur)
            // }
            // 方法三：find
            if(prev.find(item => item === cur) === undefined){
                prev.push(cur)
            }
            return prev
        },[])
        // console.log('myOrderedArray:',myOrderedArray)
        // 方法二
        let arr1 = [1,2,1,2,3,5,4,5,3,4,4,4,4];
        let result = arr.sort().reduce((prev,cur) => {
            if(prev.length === 0 || prev[prev.length-1] !== cur){
                prev.push(cur)
            }
            return prev
        },[])

        // 按属性对Object分类
        var person = [
            {name:'xiaoming',age:18},
            {name:'xiaohong',age:17},
            {name:'xiaogang',age:17}
        ];
        function groupBy(objectArray, property){
            return objectArray.reduce((prev,cur) => {
                var key = cur[property];
                if(!prev[key]){
                    prev[key] = []
                }
                prev[key].push(cur);
                return prev
            },{})
            var groupedPerson = groupBy(person,'age');
        }

        // 对对象的属性求和
        let people = [
            {name:'Alice',age:21},
            {name:'Max',age:20},
            {name:'Jane',age:20}
        ];
        let result1 = people.reduce((prev,cur) => prev + cur.age,0)
        console.log('result1:',result1)
        
    </script>
</body>
</html>